<template>
    <div class="singer-table">
        <div class="singer-container">
            <div class="handle-box">
                <el-input v-model="select_word" size='mini' placeholder="请输入歌曲名" class="handle-input"/>
                <el-button type="primary" size="mini" @click="addSongDialog = true">添加歌曲</el-button>
                <el-button type="danger" size="mini" @click="delAll">批量删除</el-button>
            </div>
        </div>

        <el-table size="mini" class="singertables" border :data="data" @selection-change="handleSelectionChange">
            <el-table-column type="selection"  width="40"></el-table-column>
            <el-table-column label="歌曲图片" width="110" align="center">
                <template v-slot='scope'>
                    <div class="song-image">
                        <img :src="getUrl(scope.row.pic)" alt="">
                        <div class="play">
                            <i 
                            @click="setSongUrl(scope.row.url,scope.row.name)" 
                            class="iconfont" 
                            :class="[(toggle===scope.row.name && isPlay === true) ? 'icon-iconstop' : 'icon-play1']">
                            </i>
                        </div>
                    </div>
                    <el-upload 
                    :action="uploadUrl(scope.row.id)" 
                    :on-success="handleAvatorSuccess" 
                    :before-upload="beforeAvatorUpdate">
                        <el-button size="mini">更新图片</el-button>
                    </el-upload>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="歌名" width="120" align="center"></el-table-column>
            <el-table-column prop="introduction" label="专辑" width="150" align="center"></el-table-column>

            <el-table-column label="歌词" align="center">
                <template v-slot="scope">
                    <ul style="height:100px;overflow-y:scroll">
                        <li v-for="(item,index) in filterSyic(scope.row.lyic)" :key="index">
                            {{item}}
                        </li>
                    </ul>
                    
                </template>
            </el-table-column>
            <el-table-column width="120" label="更新歌曲资源" align="center">
                <template v-slot='scope'>
                    <el-upload 
                    :action="uploadSongUrl(scope.row.id)" 
                    :on-success="handleAvatorSuccess"
                    :before-upload="beforeUploadSong">
                        <el-button size="mini">更新歌曲</el-button>
                    </el-upload>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="150">
                <template v-slot="scope">
                    <el-button size="mini"  type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="mini"  type="danger" @click="handleDelete(scope.row.id)">删除</el-button>

                </template>
            </el-table-column>
        </el-table>

        <div class="pagination">
            <el-pagination
                background
                layout="total,prev,pager,next"
                :current-page="currentPage"
                :page-size="pageSize"
                :total="songs.length"
                @current-change="handleCurrentChange"/>
        </div>

        <el-dialog title="添加歌曲"  :visible.sync="addSongDialog" width="400px" center>

            <el-form :model="registerForm" ref="registerForm" label-width="80px" id="addSongForm">
                <el-form-item prop="name" label="歌曲名" size="mini">
                    <el-input v-model="registerForm.name" placeholder="歌曲名"></el-input>
                </el-form-item>
                <el-form-item label="歌手名" size="mini">
                    <el-select v-model="registerForm.singerId" placeholder="请选择歌手">
                        <el-option v-for="item in singers" :label="item.name" :value="item.id" :key="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="introduction" label="专辑" size="mini">
                    <el-input v-model="registerForm.introduction" placeholder="专辑"></el-input>
                </el-form-item>
                <el-form-item prop="lyic" label="歌词" size="mini">
                    <el-input type="textarea" :autosize="{minRows:2,maxRows:13}" v-model="registerForm.lyic" placeholder="歌词"></el-input>
                </el-form-item>
                <el-form-item label="歌曲文件" size="mini">
                    <input type="file" name="file"/>
                </el-form-item>
            </el-form>

            <span slot="footer">
                <el-button size="mini" @click="addSongDialog = false">取消</el-button>
                <el-button size="mini"  type="primary" @click="addSong">确定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="修改歌曲"  :visible.sync="updateSongDialog" width="400px" center>
            <el-form :model="updateForm" ref="updateForm" label-width="80px">
                <el-form-item prop="name" label="歌曲名" size="mini">
                    <el-input v-model="updateForm.name" placeholder="歌曲名"></el-input>
                </el-form-item>
                <el-form-item prop="introduction" label="专辑" size="mini">
                    <el-input v-model="updateForm.introduction" placeholder="专辑"></el-input>
                </el-form-item>
                <el-form-item prop="lyic" label="歌词" size="mini">
                    <el-input type="textarea" :autosize="{minRows:2,maxRows:13}" v-model="updateForm.lyic" placeholder="歌词"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer">
                <el-button size="mini" @click="updateSongDialog = false">取消</el-button>
                <el-button size="mini" type="primary" @click="updateSong">确定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="删除歌曲"  :visible.sync="delVisible" width="400px" center>    
            <div align="center">删除不可恢复,是否确定删除?</div>
            <span slot="footer">
                <el-button size="mini" @click="delVisible = false">取消</el-button>
                <el-button size="mini" type="primary" @click="deleteRow">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>


<script>
    import {getAllSongsByListSongId,toListSongAddSong,getAllSinger,updateSong,deleteSong,deleteSongs} from '../api/index'
    import {mapGetters} from 'vuex'
    export default {
        data () {
            return {
                songListID: -1,                         // 歌单id
                songListTitle: '',                       // 歌单名
                addSongDialog : false,                // 显示是否显示新增歌曲弹出框
                updateSongDialog: false,              // 修改歌手弹出是否显示
                delVisible: false,                    // 显示删除弹出框
                registerForm: {                       // 新增歌曲时新增的数据  
                    name: '',
                    singerId: '',
                    introduction: '',
                    lyic: '',
                },
                updateForm: {                                 // 修改用户框
                    id: -1,
                    name: '',
                    introduction: '',
                    lyic: '',
                },
                songs: [],                                          
                tempSongs: [],
                select_word: '',
                pageSize:5,             // 每页的数据量
                currentPage:1,          // 当前为第几页
                idx: -1,                // 当前选择项
                multipleSelection:[],   // 哪些项已经打钩了
                toggle: false,          // 播放器显示图标状态
                singers: []
            }
        },
        created () {

            this.songListID = this.$route.query.id
            this.songListTitle = this.$route.query.title

            this.getData()
        },
        destroyed () {
            this.$store.commit("setIsPlay",false)
        },
        methods: {
            // 添加歌曲
            addSong () {
                let form = new FormData(document.getElementById("addSongForm"))

                
                let singer = this.singers.filter(item => {
                    return item.id = this.registerForm.singerId
                })
                console.log(singer)
                // 添加歌手id
                form.append("singerId",this.registerForm.singerId)
                // 添加歌曲名
                form.append("name", singer[0].name + '-' +this.registerForm.name)
                // 添加歌词
                if(this.registerForm.lyic === '') {
                    form.set('lyic','[00:00:00]暂无歌词')
                }else{
                    form.append('lyic',this.registerForm.lyic)
                }
                // 添加简介
                form.append('introduction',this.registerForm.introduction)
                // 添加歌单id
                form.append('songListId',this.songListID)
                
                
                toListSongAddSong(form)
                    .then(res => {
                        if(res.code === 1) {
                            this.getData()
                            this.registerForm = {}
                            this.notify(res.msg,"success")
                        }else{
                           this.notify(res.msg,"error") 
                        }
                    })


                this.addSongDialog = false
                this.getData()


            },

            // 查询所有歌手
            allSinger () {
                getAllSinger()
                    .then(res => {
                        this.singers = res
                    })
            },

            // 查询所有歌曲
            getData () {
                // 先请空
                this.songs = []

                // 查询
                getAllSongsByListSongId(this.songListID)
                    .then(res => {
                        this.tempSongs = res
                        this.songs = res
                    })
            },
            // 上传图片
            uploadUrl (id) {
                return `${this.$store.state.HOST}/song/updateSongPic?id=${id}`
            },
            // 修改页数
            handleCurrentChange (val) {
                this.currentPage = val
            },

            // 弹出修改歌手框
            handleEdit(song) {
                this.updateSongDialog = true

                // 实现数据回显
                this.updateForm = {
                    id: song.id,
                    name: song.name,
                    introduction: song.introduction,
                    lyic: song.lyic
                }
            },

            // 提交修改信息
            updateSong () {
               

                let params = new URLSearchParams()
                params.append('id',this.updateForm.id)
                params.append('name',this.updateForm.name)
                params.append('introduction',this.updateForm.introduction)
                params.append('lyic',this.updateForm.lyic)


                updateSong(params)
                    .then(res => {
                        if(res.code === 1) {
                            this.getData()
                            this.notify("修改成功","success")
                        }else {
                            this.notify("修改失败","error")
                        }
                    })
                    .catch(err => {
                        console.log(err)
                    })

                this.updateSongDialog = false
            },

            // 删除一名歌手
            deleteRow () {
                let params = new URLSearchParams();
                params.append('id',this.idx);
                deleteSong(params)
                    .then(res => {
                        if(res.code === 1) {
                            this.notify(
                                "删除成功",
                                "success"
                            )
                            this.getData()
                        }else{
                            this.notify(
                                "删除失败",
                                "error"
                            )
                        }
                    })



                this.delVisible = false
                this.getData()
            },

            // 把已经选择的项赋值给multipleSelection
            handleSelectionChange (val) {
                this.multipleSelection = val
            },

            // 批量删除歌手
            delAll () {
                let songs = []
                this.multipleSelection.forEach((item,index) => {
                    songs[index] = item.id
                })
                
                deleteSongs(songs)
                    .then(res => {
                         if(res.code === 1) {
                            this.notify(
                                "删除成功",
                                "success"
                            )
                            this.getData()
                        }else{
                            this.notify(
                                "删除失败",
                                "error"
                            )
                        }
                    })
            },

            // 格式化歌词
            filterSyic (syic) {
                let lines = syic.split("\n")
               let pattern = /\[(\d{2}:\d{2}.\d{2})\]/g
               let result = []
               for(let item of lines) {
                   let value = item.replace(pattern,'')
                   result.push(value)
               }
               return result
            },

            // 上传文件之前的校验
            beforeUploadSong (file) {
                let textMsg = file.name.split('.')
                console.log(textMsg)
                if(textMsg[textMsg.length - 1] !== 'mp3') {
                    this.notify("上传文件只能是mp3格式","error")
                    return false
                }

                return true

            },

            // 上传歌曲文件
            uploadSongUrl (id) {
                return `${this.$store.state.HOST}/song/updateSongUrl?id=${id}`
            },

            // 切换播放音乐
            setSongUrl (url,name) {
                if(this.toggle != name) {
                    this.$store.commit("setIsPlay",true)
                }else {
                    this.$store.commit("setIsPlay",!this.isPlay)
                }
                this.toggle = name;
                

                this.$store.commit("setSongUrl",this.$store.state.HOST + url)
            }

        },
        computed: {
            data () {
                return this.songs.slice((this.currentPage-1)*this.pageSize,this.currentPage * this.pageSize)
            },
            ...mapGetters(["isPlay"])
        },
        watch: {
            select_word (newValue,oldValue) {
                this.songs = this.tempSongs
                if(newValue !== '') {
                    this.songs = this.songs.filter((item,index) => {
                        return item.name.includes(newValue)
                    })
                }
            },

            addSongDialog (newValue) {
                if(newValue) {
                    this.allSinger()
                }
            }
        }

    }
</script>


<style scoped lang="less">
    .singer-table{
        min-width: 800px;
        .singer-container{
            padding: 20px;
            border:1px solid #ddd;
            background-color: #fff;
            border-radius: 5px;
            .handle-box {
                margin-bottom: 20px;
                .handle-input{
                    width: 300px;
                    display: inline-block;
                }
            }
        }
        .song-image{
            position: relative;
            width: 100%;
            height: 80px;
            border-radius: 5px;
            margin-bottom: 5px;
            overflow: hidden;
            img{
                display: block;
                width: 100%;
                height: 100%;
            }
            .play{
                position: absolute;
                left: 0;
                top: 0;
                bottom: 0;
                right: 0;
                margin: auto;
                z-index: 100;
                width: 20px;
                height: 20px;
                i{
                    display: inline-block;
                    width: 100%;
                    height: 100%;
                    font-size: 25px;
                    color: #ccc;
                    opacity: 0.8;
                    cursor: pointer;
                }
            }
        }
        .singertables{
            width:100%;
            height:calc(100vh - 210px);
            overflow-y: scroll
        }
        .pagination{
            display: flex;
            height: 50px;
            justify-content: center;
            background-color: #fff;
            align-items: center;
        }
    }
</style>